package com.cqc.other;

import org.junit.Test;

import java.util.*;

public class ListTest {

    @Test
    public void f1() {
        ArrayList<String> listA = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            listA.add(i+"");
        }
        List<String> listB = new ArrayList<>();
        for (int i = 0; i < 100000; i++) {
            listB.add(i+"");
        }
        long start = System.currentTimeMillis();
        boolean equalCollection = isEqualCollection(listA, listB);
        long cost = System.currentTimeMillis() - start;
        System.out.println("A和B是否相等：" + equalCollection + "，耗时：" + cost + "ms");
        List<String> strings = listA.subList(1, 2);
    }

    /**
     * 比较两个集合是否相等,简化复杂度，m*n减少到 m+n+x(x<m)
     *
     * @param a
     * @param b
     * @return
     */
    public boolean isEqualCollection(List<String> a, List<String> b) {
        if (a.size() != b.size()) {
            return false;
        }
        Map<String,Integer> mapA = new HashMap<String,Integer>();
        for (String key : a) {
            mapA.merge(key, 1, Integer::sum);
        }
        System.out.println("$$$="+mapA.get("0"));

        Map<String,Integer> mapB = new HashMap<String,Integer>();
        for (String key : b) {
            mapB.merge(key, 1, Integer::sum);
        }

        if (mapA.size() != mapB.size()) {
            return false;
        }

        for (String obj : mapA.keySet()) {
            if (mapA.get(obj).intValue() != (mapB.get(obj)).intValue()) {
                return false;
            }
        }
        return true;

    }



}
